﻿using BootyBay.PrivateStoreApp.AgentServicesRef;
using BootyBay.PrivateStoreApp.Common;
using BootyBay.PrivateStoreApp.DataModel;
using BootyBay.PrivateStoreApp.StoreServicesRef;
using BootyBay.PrivateStoreApp.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace BootyBay.PrivateStoreApp
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class YourAppsPage : Page
    {

        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// 可将其更改为强类型视图模型。
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper 在每页上用于协助导航和
        /// 进程生命期管理
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        public YourAppsPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
            AppDetailPageVM.Instance.InstallrefreshData.CollectionChanged -= InstallrefreshData_CollectionChanged;
            AppDetailPageVM.Instance.InstallrefreshData.CollectionChanged += InstallrefreshData_CollectionChanged;

            AppListPageVM.Instance.AppData.CollectionChanged -= AppData_CollectionChanged;
            AppListPageVM.Instance.AppData.CollectionChanged += AppData_CollectionChanged;
            LoadInfo();
        }

        void AppData_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            LoadInfo();
        }

        #region 应用安装成功后刷新下载列表
        void InstallrefreshData_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            LoadInfo();
        }
        #endregion

        #region 加载信息
        private async void LoadInfo()
        {
            try
            {
                AppListPageVM yourAppsPageVM = await AppDetailPageVM.Instance.GetAppsInfoByStatus(AppLocalStatus.Installed, true);
                txt_AppNumber.Text = yourAppsPageVM.AppData.Count.ToString();
                txt_UserName.Text = App.CurrentUserName;
                this.DataContext = yourAppsPageVM;
                itemGridView.ItemsSource = yourAppsPageVM.AppData;
            }
            catch (System.InvalidOperationException)
            {

            }
        }
        #endregion

        /// <summary>
        ///使用在导航过程中传递的内容填充页。 在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="sender">
        /// 事件的来源; 通常为 <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">事件数据，其中既提供在最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数，又提供
        /// 此页在以前会话期间保留的状态的
        /// 的字典。 首次访问页面时，该状态将为 null。</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。  值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        ///<param name="sender">事件的来源；通常为 <see cref="NavigationHelper"/></param>
        ///<param name="e">提供要使用可序列化状态填充的空字典
        ///的事件数据。</param>
        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper 注册

        /// 此部分中提供的方法只是用于使
        /// NavigationHelper 可响应页面的导航方法。
        /// 
        /// 应将页面特有的逻辑放入用于
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// 和 <see cref="GridCS.Common.NavigationHelper.SaveState"/> 的事件处理程序中。
        /// 除了在会话期间保留的页面状态之外
        /// LoadState 方法中还提供导航参数。

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        #region 全选/反选应用
        private void btn_SelectAll_Click(object sender, RoutedEventArgs e)
        {
            if (btn_SelectAll.IsChecked == true)
            {
                btn_SelectAll.Content = "清除";
                foreach (var item in itemGridView.Items)
                {
                    itemGridView.SelectedItems.Add(item);
                }
            }
            else
            {
                btn_SelectAll.Content = "全选";
                itemGridView.SelectedItems.Clear();
            }

        }
        #endregion

        #region 卸载应用
        /// <summary>
        /// Modified and Simplified the logic by Ranger. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_UnInstall_Click(object sender, RoutedEventArgs e)
        {
            int count = 0;
            foreach (UserAppDataModel item in itemGridView.SelectedItems)
            {
                Guid optGuid = await AppDetailPageVM.Instance.RequestForAppUnInstallation(item);
                //var downloadAppsToRemove = DownloadAppsPageVM.Instance.DownloadApps.Where(a => a.AppName == item.AppView.ApplicationName).FirstOrDefault();
                //DownloadAppsPageVM.Instance.DownloadApps.Remove(downloadAppsToRemove);
                if (optGuid != null)
                {
                    count++;
                    //LoadInfo();
                    //await AppDetailPageVM.Instance.LoadAppData(item);
                }
            }
            if (count > 0)
            {
                LoadInfo();
            }
        }

        void Instance_IsrefreshData()
        {

        }
        #endregion

        #region 安装应用
        private async void btn_Install_Click(object sender, RoutedEventArgs e)
        {
            foreach (UserAppDataModel userAppDataModel in itemGridView.SelectedItems)
            {
                if (userAppDataModel != null)
                {
                    AppDetailPageVM appDetailPageVM = new AppDetailPageVM();

                    await appDetailPageVM.LoadAppData(userAppDataModel);
                    btn_Install.DataContext = appDetailPageVM;
                    btn_Install.Command.Execute("true");
                }
            }
        }
        #endregion

        #region 跳转到你的应用页
        private void btn_AppList_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(YourAppsPage));
        }
        #endregion

        #region 跳转到主页
        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));

        }
        #endregion

        #region 跳转到应用的详细页
        private void itemGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            UserAppDataModel userAppDataModel = (UserAppDataModel)e.ClickedItem;
            this.Frame.Navigate(typeof(ItemDetailPage), userAppDataModel);
        }
        #endregion

        #region 底部功能面板的显隐
        private void itemGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (itemGridView.SelectedItems.Count > 0)
            {
                grd_Panel.Visibility = Visibility.Visible;
            }
            else
            {
                grd_Panel.Visibility = Visibility.Collapsed;
            }
        }
        #endregion
    }
}
